<?php

namespace app\model;

use lib\Log;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;

class orders extends Model
{
	protected $table 		= 'orders';
	protected $primaryKey	= 'id';
	protected $appends 		= ['status_name'];

	public function getStatusNameAttribute()
	{
		$statusName = '';
		switch($this->attributes['status']){
				case '100':
					$statusName	=	'待付款';
					break;
				case '200':
					if($this->attributes['shipping_type']==3){
						$statusName	=	'已完成';
					}else{
						$statusName	=	'待发货';
					}
					break;
				case '300':
					$statusName	=	'已取消';
					break;
				case '400':
					$statusName	=	'待收货';
					break;
				case '500':
					$statusName	=	'待评价';
					break;
				case '600':
					$statusName	=	'退款中';
					break;
                case '700':
                    $statusName	=	'已退款';
                    break;
                case '800':
                    $statusName	=	'已完成';
                    break;
			}
		return $statusName;
	}

	public static function notifyProcess($type, $params){
		Log::out("【支付成功】:\n".json_encode($params, JSON_UNESCAPED_UNICODE)."\n", $type);
		if(strtoupper($type)=='ALI'){
			$paid_type	= 1;
			$order_no	= $params['out_trade_no'];	//商户订单号_内部订单号
			$amount		= $params['total_amount'] * 100;
			$trade_no	= $params['trade_no'];
		}else{
			$paid_type	= 2;
			$order_no 	= substr($params["out_trade_no"], 0, 20);
			$amount		= $params['total_fee'];
			$trade_no	= $params['transaction_id'];
		}
		return self::notifyBody($paid_type, $order_no, $amount, $trade_no, $params["out_trade_no"]);
	}

	private static function notifyBody($paid_type, $order_no, $amount, $trade_no, $out_trade_no){
		$orders = DB::table('orders')->where('order_no', $order_no)->first();
		if (empty($orders)){return FALSE;}
		if (bccomp($orders['amount']*100, $amount)!==0){return FALSE;}
		if ($orders['status'] > 100) {return TRUE;}
		try {
			DB::beginTransaction();
			/***1.更新order表***/
			$rows = array(
				'status'		    =>	200,
				'paid_type'		    =>	$paid_type,
				'paid_at'		    =>	date('Y-m-d H:i:s'),
				'transaction_no'	=>	$trade_no,
				'out_trade_no'      =>	$out_trade_no,
			);
			DB::table('orders')->where('order_no', '=', $order_no)->update($rows);
			DB::commit();
			return TRUE;
		} catch (Exception $e) {
			DB::rollBack();
			return FALSE;
		}
	}


}
